package com.dpiinc.TechPage.utils

import android.content.Context
import com.czt.mp3recorder.Mp3Recorder
import com.czt.mp3recorder.Mp3RecorderUtil
import java.io.File
import java.io.IOException

/**
 * 录音
 * Created by X on 2018/7/15.
 */
@Suppress("unused")
object AudioRecordHelper {

    private const val MAX_RECORD_TIME = 2 * 60 * 60//两小时
    private var mRecorder: Mp3Recorder? = null
    private var outputFile: File? = null

    fun init(context: Context, isDebug: Boolean) {
        Mp3RecorderUtil.init(context, isDebug)
    }

    private fun initRecorder(outputFile: File): Mp3Recorder? {
        this.outputFile = outputFile
        mRecorder = Mp3Recorder()
        mRecorder?.setOutputFile(outputFile.path)
                ?.setMaxDuration(MAX_RECORD_TIME)//录音最大时长,达到后自动停止录音.
        return mRecorder
    }

    fun startRecord(outputFile: File, callback: Mp3Recorder.Callback): Mp3Recorder? {
        initRecorder(outputFile)
        try {
            mRecorder?.setCallback(callback)
            //TODO AudioRecorder 270行，文件创建不成功的时候会报空指针
            mRecorder?.start()
            return mRecorder
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }

    fun endRecord(): File? {
        return try {
            mRecorder?.stop(Mp3Recorder.ACTION_STOP_ONLY)
            outputFile
        } catch (e: IOException) {
            e.printStackTrace()
            null
        }
    }

    fun getRecorder(): Mp3Recorder? {
        return mRecorder
    }

    fun getState(): Int {
        return mRecorder?.recorderState ?: Mp3Recorder.State.UNINITIALIZED
    }
}